<template>
  <div class="echarts" ref="chartsRef" />
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import echarts from '@/views/components/dataScreen/echarts'

const props = defineProps({
  options: {
    type: Object,
    required: true
  },
  height: {
    type: String,
    default: '100%'
  }
})

const chartsRef = ref(null)
let chart = null

const initChart = () => {
  if (!chartsRef.value) return
  chart = echarts.init(chartsRef.value)
  chart.setOption(props.options)
  return chart
}

const resizeChart = () => {
  if (chart) {
    chart.resize()
  }
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', resizeChart)
})

watch(() => props.options, (newOptions) => {
  if (chart && newOptions) {
    chart.setOption(newOptions)
  }
}, { deep: true })
</script>
<style lang="scss" scoped>
.echarts {
  height: v-bind(height);
  width: 100%;
}
</style>
